<?php

namespace app\api\controller;

use app\api\basic\BaseController;
use support\Request;
use app\activity\logic\activityLogic;
use app\matchingRule\logic\MatchingRuleLogic;
use app\policyMatching\logic\PolicyMatchingLogic;
use app\signup\logic\signupLogic;
use app\api\annotation\LoginRequired;
use think\facade\Db;

//政策查询

class MatchingRuleController extends BaseController {
     protected $userInfo;

    /**
     * 当前登陆管理员ID
     */
    protected $userId;

    /**
     * 当前登陆管理员账号
     */
    protected $userName;
    public function __construct()
    {   
        parent::__construct();
        $this->userId=request()->userId;
        $this->userName=request()->userName;
        $this->userInfo=request()->userInfo;
    }
    #[LoginRequired(required:false)]
    public function Lists(Request $request){
        $time=[
           'week'=>7,
           'month'=>30 
        ];
        $param = $request->more([
            ['lang_code','zh'],
            ['limit',10],
            ['province_id',''],
            ['city_id',''],
            ['district_id',''],
            ['xz_level',''],
            ['page',1],
            ['day',''],
            ['selectOption',''],
            ['policy_title','']
        ]);
        if(in_array($param['day'],['week','month'])){
            $timestamp = strtotime("-{$time[$param['day']]} days");
            $param['day'] = date('Y-m-d H:i:s', $timestamp);
        }
        $PolicyMatchingLogic = new PolicyMatchingLogic();
        $MatchingRuleLogic = new MatchingRuleLogic();
        $query=$PolicyMatchingLogic->search([
            'province_id'=>$param['province_id'],
            'city_id'=>$param['city_id'],
            'district_id'=>$param['district_id'],
            'xz_level'=>$param['xz_level'],
            'lang_code'=>$param['lang_code'],
            'is_display'=>1
        ]);
        if($param['day']){
            $query=$query->where('create_time','>=',$param['day']);
        }
        if($param['policy_title']){
            $query->where('policy_title|application_conditions', 'like', "%{$param['policy_title']}%");

        }
        if($param['selectOption']){
           $MatchingRuleList=$MatchingRuleLogic->whereIn('rule_id',$param['selectOption'])->select();
           if(!$MatchingRuleList)return $this->success(['data'=>'','total'=>0],'暂无政策');
           
           $industry_category_search=[];
           //获取强匹配条件
           foreach($MatchingRuleList as $item){
                if($item->rule_type==0){
                    $industry_category_search[]=$item->rule_id;
                }
           }
         
           $matching_id_search=[];
           //获取关联数据
           if($industry_category_search){
            $matching_id_search=Db::table('eb_policy_matching_search')
            ->whereIn('industry_category_id',$industry_category_search)
            ->column('matching_id');
           }
           //获取匹配政策
           if($matching_id_search){
            $query=$query->whereIn('matching_id',$matching_id_search);
           }
           

        }
        $data=$query->
        field('matching_id,policy_title,province_id,city_id,district_id
        ,application_start_time,application_end_time,is_display,source,
        status,create_time')
        //->order('status desc')
            ->order('sort_order desc')
            ->order('create_time desc')
        ->paginate($param['limit']);
        $list=$data->items();
        foreach($list as &$item){
                  $now = strtotime(date('Y-m-d H:i:s'));
                  $startTime = strtotime($item['application_start_time']);
                  $endTime = strtotime($item['application_end_time']);

                  if ($now < $startTime) {
                    $item['time_text'] = '未开始';
                    $item['remaining_time_text'] = 0;
                  } elseif ($now > $endTime) {
                    $item['time_text'] = '已结束';
                    $item['remaining_time_text'] = 0;
                  } else {
                    $item['time_text'] = '进行中';
                    // 计算剩余天数，结果向上取整
                    $item['remaining_time_text'] = ceil(($endTime - $now) / (60 * 60 * 24));
                  }    
          
        }
        unset($item);

        return $this->success(['data'=>$list,'total'=>$data->total()]);
        
    }
    /**
     * 活动详情
     */
    #[LoginRequired(required:false)]
    public function details(Request $request){
        $param = $request->more([
            ['matching_id',''],
        ]);
        $PolicyMatchingLogic = new PolicyMatchingLogic();
        $MatchingRuleLogic = new MatchingRuleLogic();
        $data=$PolicyMatchingLogic->search([
            'matching_id'=>$param['matching_id'],
            'is_display'=>1
        ])->field('matching_id,policy_title,province_id,city_id,district_id
        ,application_start_time,application_end_time,is_display,source,
        status,create_time,application_conditions,industry_category,lang_code')->find();
        if($data){
            $data=$data->toArray();
            if($data['industry_category']){
                  $allValues = [];
                   foreach ($data['industry_category'] as $key => $value) {
                       if($value){
                           $allValues[]=$key;
                           foreach($value as $k=>$v){
                               $allValues[]=$v;
                           }
                       }


                }
                 $rule_name = 'rule_name_'.$data['lang_code'];
                 $MatchingRuleList = $MatchingRuleLogic->whereIn('rule_id',$allValues)->field("{$rule_name} as rule_name,rule_id,parent_id")->order('rule_sort desc')->select()->toArray();
               
                 $data['MatchingRuleTree'] = $MatchingRuleLogic->buildTree($MatchingRuleList, 0);

                 //查询是否申报
                $data['is_application'] =0;//未申报
                 $db = Db::table('eb_policy_application');
                 $applicationCount = $db->where(['matching_id'=>$data['matching_id'],'user_id'=>$this->userId])->whereNull('delete_time')->count();
                 if($applicationCount >0){
                     $data['is_application'] =1;
                 }


                
            }
            return $this->success($data);

        }
        return $this->fail('数据不存在');
    }
    #[LoginRequired(required:false)]
    public function policy_matching(Request $request){
        $param = $request->more([
            ['lang_code','zh'],
        ]);
        $MatchingRuleLogic = new MatchingRuleLogic();
        $rule_name = 'rule_name_'.$param['lang_code'];
        $list = $MatchingRuleLogic->field("{$rule_name} as rule_name,rule_id,parent_id")->order('rule_sort desc')->select()->toArray();
       
        // 构建树形结构
        $tree = $MatchingRuleLogic->buildTree($list, 0);
      
        // 过滤没有子级的一级节点
        $tree = array_filter($tree, function($item) {
            return isset($item['children']);
        });
        return $this->success($tree);
    }

    //政策申报

    public  function  sbRule(Request $request){
        $param = $request->more([
            ['matching_id',''],
            ['company_name',''],
            ['credit_code',''],
            ['name',''],
            ['phone',''],
            ['position',''],
        ]);
        $param['user_id'] = $this->userId;
        $param['create_time'] = date('Y-m-d h:i:s',time());
        $db = Db::table('eb_policy_application');
        $res = $db->insert($param);
        if($res){
            return $this->success('申报成功');
        }else{
            return  $this->fail('申报失败');
        }
    }

    //政策申报列表
    public function sbRuleList(Request $request){
        $param = $request->more([
            ['page',''],
            ['limit',''],
        ]);
       // $user_id =65;
       $user_id =$this->userId;
        $db = Db::table('eb_policy_application');
        $res = $db->where(['user_id'=>$user_id])->paginate($param['limit']);
        $list=$res->items();
      ///  print_r($list);
        foreach ($list as $key => &$val){
            $MatchingRuleLogic = new PolicyMatchingLogic();
            $all = $MatchingRuleLogic->where(['matching_id'=>$val['matching_id']])->find()->toArray();
           // print_r($all);
            $val['range_time'] =$all['application_start_time']."-".$all['application_end_time'];
            //通过开始时间和姐结束时间计算 还剩下多少天结束 2025-08-01 - 2025-11-
            $now = strtotime(date('Y-m-d H:i:s'));
            $startTime = strtotime($all['application_start_time']);
            $endTime = strtotime($all['application_end_time']);
            if ($now < $startTime) {
                $val['time_text'] = '未开始';
                $val['remaining_time_text'] = 0;
            } elseif ($now > $endTime) {
                $val['time_text'] = '已结束';
                $val['remaining_time_text'] = 0;
            } else {
                $val['time_text'] = '进行中';
                // 计算剩余天数，结果向上取整
                $val['remaining_time_text'] = ceil(($endTime - $now) / (60 * 60 * 24));
            }
            $val['title'] =$all['policy_title'];
            $val['source'] =$all['source'];
        }
        return $this->success(['data'=>$list,'total'=>$res->total()]);

    }



}